let installed = false
let _Vue = null

class hashVueRouter {
  //这个是当运行Vue.use的时候调用的函数，作用是把vueRouter相关信息配置到全局
  static install(Vue) {
    //使用标志位进行判断：是否已经运行过Vue.use函数
    if (installed) return
    installed = true
    _Vue = Vue
    _Vue.mixin({
      //将相关信息在beforeCreate阶段进行混入
      beforeCreate() {
        //这句话是用来判断是否在vue实例上的
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
        }
      }
    })
  }

  constructor(options) {
    //如果没有hash的话自动加上hash
    if (window.location.hash === "") window.location.hash = "/"
    this.options = options
    this.routerMap = {}
    this.data = _Vue.observable({
      current: window.location.hash.substr(1)
    })
    console.log(this.data.current)
    // this.data = {current:"/"}
    this.init()
  }

  init() {
    //向url中加入#
    // if(window.location.hash === '')window.location.hash="/#/"
    //初始化routerMap的映射
    this.createRouteMap()
    //初始化组件
    this.initComponent(_Vue)
    //初始化监听事件
    this.initOnHashChange()
  }

  createRouteMap() {
    this.options.routes.forEach(route => {
      this.routerMap[route.path] = route.component
    })
  }

  initComponent(Vue) {
    Vue.component("router-link", {
      props: {
        to: String
      },
      render(h) {
        return h("a", {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickhander
          }
        }, [this.$slots.default])
      },
      methods: {
        clickhander(e) {
          window.location.hash = this.to
          e.preventDefault()
        }
      }
    })
    const self = this
    console.log("self", self)
    Vue.component("router-view", {
      render(h) {
        //在这用的响应式数据
        const cm = self.routerMap[self.data.current]
        return h(cm)
      }
    })
  }

  initOnHashChange() {
    window.addEventListener("hashchange", () => {
      this.data.current = window.location.hash.substr(1)
      console.log(this.data.current)
    })
  }
}

export default hashVueRouter
